package com.innovation.ic.b1b.monitor.base.service.masterSlave.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.innovation.ic.b1b.monitor.base.mapper.RedisMapper;
import com.innovation.ic.b1b.monitor.base.model.Redis;
import com.innovation.ic.b1b.monitor.base.model.RedisAvailableJob;
import com.innovation.ic.b1b.monitor.base.pojo.RedisPojo;
import com.innovation.ic.b1b.monitor.base.pojo.constant.TableNameConstant;
import com.innovation.ic.b1b.monitor.base.pojo.variable.ServiceResult;
import com.innovation.ic.b1b.monitor.base.pojo.variable.redis.RedisInfoRespPojo;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.EnvironmentService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.RedisAvailableJobLogHistoryService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.RedisAvailableJobLogService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.RedisAvailableJobService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.RedisService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.ServiceHelper;
import com.innovation.ic.b1b.monitor.base.vo.RedisVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class RedisServiceImpl extends ServiceImpl<RedisMapper, Redis> implements RedisService {

    @Resource
    private EnvironmentService environmentService;

    @Resource
    private RedisAvailableJobService redisAvailableJobService;

    @Resource
    private RedisAvailableJobLogService redisAvailableJobLogService;

    @Resource
    private RedisAvailableJobLogHistoryService redisAvailableJobLogHistoryService;

    @Resource
    private ServiceHelper serviceHelper;


    @Override
    public ServiceResult addRedis(RedisVo redisVo) {
        ServiceResult serviceResult = new ServiceResult();
        Integer id = redisVo.getId();
        Redis redis = new Redis();
        BeanUtil.copyProperties(redisVo, redis);
        QueryWrapper<Redis> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("redis_database", redisVo.getRedisDatabase());
        queryWrapper.eq("nodes", redisVo.getNodes());
        if (id == null) {
            List<Redis> redisList = this.baseMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(redisList)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("重复,请重新添加");
                return serviceResult;
            }
            QueryWrapper<Redis> queryWrapperName = new QueryWrapper<>();
            queryWrapperName.eq("name", redisVo.getName());
            List<Redis> redisNameList = this.baseMapper.selectList(queryWrapperName);
            if (!CollectionUtils.isEmpty(redisNameList)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("名字不能重复");
                return serviceResult;
            }
            this.baseMapper.insert(redis);
        } else {
            queryWrapper.ne("id", id);
            List<Redis> redisList = this.baseMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(redisList)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("重复,请重新添加");
                return serviceResult;
            }
            QueryWrapper<Redis> queryWrapperName = new QueryWrapper<>();
            queryWrapperName.eq("name", redisVo.getName());
            queryWrapperName.ne("id", id);
            List<Redis> redisNameList = this.baseMapper.selectList(queryWrapperName);
            if (!CollectionUtils.isEmpty(redisNameList)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("名字不能重复");
                return serviceResult;
            }
            this.baseMapper.updateById(redis);
        }
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage("成功");
        return serviceResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRedis(RedisVo redisVo) {
        Integer id = redisVo.getId();
        this.baseMapper.deleteById(id);
        this.deleteByRedisId(id);
    }

    @Override
    public ServiceResult<PageInfo<RedisPojo>> findByPage(RedisVo redisVo,Boolean mainDb) {
        ServiceResult<PageInfo<RedisPojo>> serviceResult = new ServiceResult<>();
        Integer environmentId = redisVo.getEnvironmentId();
        if (environmentId != null) {
            List<Integer> environmentIds = environmentService.findByName(environmentId);
            if (!CollectionUtils.isEmpty(environmentIds)) {
                redisVo.setEnvironmentIds(environmentIds);
            }
        }
        PageHelper.startPage(redisVo.getPageNo(), redisVo.getPageSize());
        List<RedisPojo> redisPojoList = this.baseMapper.findByPage(redisVo);
        PageInfo<RedisPojo> pageInfo = new PageInfo<>(redisPojoList);
        serviceResult.setResult(pageInfo);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 查询redis信息列表
     *
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<RedisInfoRespPojo>> queryRedisList(Boolean mainDb) {
        List<RedisInfoRespPojo> result = this.baseMapper.queryRedisList();
        ServiceResult<List<RedisInfoRespPojo>> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    @Override
    public void deleteByEnvironmentId(Integer environmentId) {
        QueryWrapper<Redis> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("environment_id", environmentId);
        List<Redis> redisList = this.baseMapper.selectList(queryWrapper);
        for (Redis redis : redisList) {
            this.deleteByRedisId(redis.getId());
        }
        Map<String, Object> param = new HashMap<>();
        param.put("environment_id", environmentId);
        this.baseMapper.deleteByMap(param);
    }


    /**
     * 级联删除redis关联
     *
     * @param redisId
     */
    private void deleteByRedisId(Integer redisId) {
        //删除定时任务
        Map<String, Object> sqlServerIdMap = new HashMap<>();
        sqlServerIdMap.put("redis_id", redisId);
        List<RedisAvailableJob> redisAvailableJobList = redisAvailableJobService.findByRedisId(redisId);
        for (RedisAvailableJob redisAvailableJob : redisAvailableJobList) {
            Integer redisAvailableJobId = redisAvailableJob.getId();
            String jobId = TableNameConstant.RABBITMQ_AVAILABLE_JOB + "_" + redisAvailableJobId;
            serviceHelper.getQuartzManager().deleteScheduleJob(jobId);
            redisAvailableJobService.delete(redisAvailableJobId);
            //同时删除日志和历史日志
            redisAvailableJobLogService.deleteByRedisAvailableJobId(redisAvailableJobId);
            redisAvailableJobLogHistoryService.deleteByRedisAvailableJobId(redisAvailableJobId);
        }
    }


}
